<template>
  <div class="searchGroup">
    <div class="sg-wrapper" v-loading="tabLoading">
      <div class="sg-tabs">
        <el-tabs v-model="queryType" @tab-click="handleClick">
          <el-tab-pane label="字段组合检索" name="1">
            <!-- :key="tableKey" -->
            <el-table
              v-show="showTabs"
              :data="screenField"
              style="width: 100%"
              :border="false"
            >
              <el-table-column prop="relation" label="关系" width="100">
                <template slot-scope="scope">
                  <el-select
                    v-if="scope.$index != 0"
                    v-model="scope.row.relation"
                    placeholder="请选择关系"
                  >
                    <el-option
                      v-for="item in relationList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="field" label="字段" width="200">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.field"
                    :key="tableKey"
                    placeholder="请选择字段"
                    @change="selectChange(scope)"
                  >
                    <el-option
                      v-for="item in fieldList"
                      :key="item.databaseField"
                      :label="item.showField"
                      :value="item.databaseField"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="opration" label="运算符" width="160">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.opration"
                    placeholder="请选择运算符"
                  >
                    <el-option
                      v-for="item in operatorList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="values" label="关键词" width="300">
                <template slot-scope="scope">
                  <!-- 根据字段进行展示 -->
                  <el-date-picker
                    v-if="scope.row.dataType == 'TimeStr'"
                    v-model="scope.row.values"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择日期"
                    clearable
                  ></el-date-picker>
                  <el-select
                    v-else-if="scope.row.dataType == 'List'"
                    v-model="scope.row.values"
                    placeholder="请选择"
                    clearable
                    filterable
                    remote
                    :remote-method="
                      (query) => {
                        remoteMethod(query, scope.row.field);
                      }
                    "
                  >
                    <el-option
                      v-for="item in selectInfo[scope.row.field] || []"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-else
                    v-model="scope.row.values"
                    clearable
                    placeholder="请输入关键词"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="">
                <template slot-scope="scope">
                  <el-button
                    icon="el-icon-plus"
                    @click="addRow(scope.$index)"
                  ></el-button>
                  <el-button
                    v-if="scope.$index != 0"
                    icon="el-icon-minus"
                    @click="reduceRow(scope.$index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane class="tabZn" label="智能组合检索" name="2">
            <div v-show="showTabs">
              <p>
                <span class="span">包含全部关键词：</span
                ><el-input
                  class="largeInput"
                  clearable
                  v-model="zn.accurateSearch"
                  placeholder="请输入关键词，多个词使用，分隔"
                ></el-input>
              </p>
              <p>
                <span class="span">包含任意关键词：</span
                ><el-input
                  class="largeInput"
                  clearable
                  v-model="zn.includeSearch"
                  placeholder="请输入关键词，多个词使用，分隔"
                ></el-input>
              </p>
              <p>
                <span class="span">不包含任意关键词：</span
                ><el-input
                  class="largeInput"
                  v-model="zn.notIncludeSearch"
                  clearable
                  placeholder="请输入关键词，多个词使用，分隔"
                ></el-input>
              </p>
            </div>
          </el-tab-pane>
          <el-tab-pane class="tabBds" label="表达式检索" name="3">
            <div v-show="showTabs">
              <el-radio-group v-model="bds.whereToShow">
                <el-radio label="0">标题或正文</el-radio>
                <el-radio label="1">仅限标题</el-radio>
                <el-radio label="2">仅限正文</el-radio>
              </el-radio-group>
              <el-input
                class="textarea"
                type="textarea"
                v-model="bds.keywords"
                placeholder=""
                :autosize="{ minRows: 2, maxRows: 10 }"
                clearable
              ></el-input>
              <p>
                *自定义检索使用引号标记"关键词"，连接符使用and/or/not，连接符与关键词之间留一个空格，不同层级表达式可以使用括号表示，所有符号均为英文状态。
              </p>
              <p>举例：(("上海" or "北京") and ("电动汽车" and "充电"))</p>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="指定数据源" name="4">
            <div class="sjy-con" v-show="showTabs">
              <div class="sjy" v-for="(item, idx) in sjyList" :key="idx">
                <p>
                  <span>{{ item.title }}</span
                  ><el-checkbox
                    class="selectAll"
                    v-model="item.selectVal"
                    :true-label="1"
                    :false-label="0"
                    @change="valChange(idx)"
                    >全选</el-checkbox
                  >
                </p>
                <el-checkbox-group
                  class="checkboxGroup"
                  v-model="item.selectList"
                >
                  <el-checkbox
                    v-for="item in item.list"
                    :label="item"
                    :key="item"
                    @change="checkChange"
                    >{{ item }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </div>
          </el-tab-pane> -->
        </el-tabs>
        <div class="sg-show" @click="showTabs = !showTabs">
          <el-button type="text">{{ showTabs ? "收起" : "展开" }}</el-button>
          <i
            :class="[showTabs ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"
          ></i>
        </div>
      </div>
      <div class="ds flex" v-if="showTabs && sjyList.length">
        <p class="bold">指定数据源：</p>
        <div class="flex-auto">
          <div class="flex" v-if="sjyList[0].selectList.length">
            <p class="bold">新闻网站：</p>
            <p class="flex-auto">{{ sjyList[0].selectList.join("、") }}</p>
          </div>
          <div class="flex" v-if="sjyList[1].selectList.length">
            <p class="bold">微信公众号：</p>
            <p class="flex-auto">{{ sjyList[1].selectList.join("、") }}</p>
          </div>
        </div>
      </div>
      <div class="btnGroup" v-show="showTabs">
        <div class="btnLeft">
          <el-button type="primary" @click="dataSource">指定数据源</el-button>
        </div>
        <div class="btn">
          <el-button class="save" @click="addColumn">保存专题</el-button>
          <el-button @click="cancelRest">取消重置</el-button>
          <el-button type="primary" @click="search">确定检索</el-button>
        </div>
      </div>
    </div>
    <el-dialog title="指定数据源" :visible.sync="dialogVisible" width="80%">
      <div class="sjy-con">
        <div class="sjy" v-for="(item, idx) in sjyList" :key="idx">
          <p>
            <span class="bold">{{ item.title }}</span
            ><el-checkbox
              class="selectAll"
              v-model="item.selectVal"
              :true-label="1"
              :false-label="0"
              @change="valChange(idx)"
              >全选</el-checkbox
            >
          </p>
          <el-checkbox-group class="checkboxGroup" v-model="item.selectList">
            <el-checkbox
              v-for="item in item.list"
              :label="item"
              :key="item"
              @change="checkChange"
              >{{ item }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer dialogClass">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
const info = {
  relation: "AND",
  field: "",
  dataType: "String",
  opration: "contains",
  values: "",
};
export default {
  props: {
    tabLoading: {
      type: Boolean,
      default: false,
    },
    writeInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      showTabs: false,
      queryType: "1",
      relationList: [
        {
          label: "且",
          value: "AND",
        },
        {
          label: "或",
          value: "OR",
        },
      ], // 关系下拉
      tableKey: new Date().getTime(),
      fieldList: [], // 字段下拉
      operatorList: [], // 运算符下拉
      selectInfo: {}, // 当字段为下拉类型时，关键词下拉
      screenField: [], // 字段组合表格数据
      zn: {
        accurateSearch: "",
        includeSearch: "",
        notIncludeSearch: "",
      }, // 智能组合数据
      bds: {
        whereToShow: "0",
        keywords: "",
      }, // 表达式检索数据
      sjyList: [
        // {
        //   title: "信息网站",
        //   selectVal: 0,
        //   selectList: [],
        //   list: [
        //     "北极星电力网",
        //     "中国储能网",
        //     "索比光伏网",
        //     "电工学习网",
        //     "南方能源观察",
        //     "中国能源网",
        //     "中国能源报",
        //     "科学网",
        //     "中国智能电工网",
        //     "国防科技信息网",
        //     "电力科技网",
        //     "能量魔方",
        //     "中国核电网",
        //     "科技日报",
        //     "上海有色金属网",
        //   ],
        // },
      ], // 指定数据源
      ztInfo: {
        ztlm: "0",
        specialColumn_name: "",
      }, // 专题栏目信息
      dialogVisible: false,
    };
  },
  watch: {
    writeInfo: {
      handler(newVal, oldVal) {
        if (Object.keys(newVal).length) {
          this.reWrite(newVal);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.screenField.push(this.copyObject(info));
    this.initData();
  },
  methods: {
    dataSource() {
      this.dialogVisible = true;
    },
    // 回写数据到检索内部
    reWrite(newVal) {
      this.cancelRest();
      this.handleClick();
      this.queryType = newVal.queryData.queryType;
      this.ztInfo = {
        ztlm: "1",
        specialColumn_name: newVal.name,
      };
      if (this.queryType == 1) {
        this.screenField = newVal.queryData.screenField;
      } else if (this.queryType == 2) {
        let sf = this.copyObject(newVal.queryData);
        delete sf.queryType;
        Object.assign(this.zn, sf);
      } else if (this.queryType == 3) {
        let sf = this.copyObject(newVal.queryData);
        delete sf.queryType;
        Object.assign(this.bds, sf);
      } else if (this.queryType == 4) {
      }
      // 回写过后自动刷新页面
      this.search();
    },
    // 字段下拉变化时，切换关键词展示类型：String、List、TimeStr
    selectChange(info) {
      let row = info.row;
      row.dataType = this.fieldList.find((list) => {
        return list.databaseField == row.field;
      }).dataType;
      // console.log(row);
      if (
        row.dataType == "List" &&
        !this.selectInfo.hasOwnProperty(row.filed)
      ) {
        this.remoteMethod("", row.field);
      }
    },
    // 关键词--远程搜索
    remoteMethod(str = "", field) {
      // let param = {
      //   size: 20,
      //   name: str,
      //   databaseField: field,
      //   not_names: [],
      // };
      // this.$post(this.$Url.consultModule.queryDynamicAggList, param)
      //   .then((res) => {
      //     let data = res.data;
      //     this.selectInfo[field] = data;
      //     this.tableKey = new Date().getTime();
      //   })
      //   .catch((err) => {});
      this.queryAggList(str, field).then((data) => {
        // console.log(data);
        this.selectInfo[field] = data;
        this.tableKey = new Date().getTime();
      });
    },
    //
    queryAggList(name = "", field, not_names = []) {
      let param = {
        size: 20,
        databaseField: field,
        name: name,
        not_names: not_names,
      };
      if (field == "types") {
        param.size = 100;
        param.agg_name = "source";
        param.not_agg_names = [""];
      }
      return this.$post(this.$Url.consultModule.queryDynamicAggList, param)
        .then((res) => {
          let data = res.data;
          return data;
        })
        .catch((err) => {});
    },
    setSjyList(index, title, list = []) {
      let info = {
        title: title,
        selectVal: 0,
        selectList: [],
        list: list,
      };
      this.sjyList[index] = info;
    },
    initData() {
      // 微信公众号
      this.queryAggList("微信公众号", "types").then((data) => {
        this.setSjyList(1, "微信公众号", data);
      });
      // 新闻网站
      this.queryAggList("", "types", ["微信公众号"]).then((data) => {
        this.setSjyList(0, "新闻网站", data);
      });
      this.$get(this.$Url.consultModule.queryDataSetField)
        .then((res) => {
          let data = res.data;
          if (data.length) {
            this.operatorList = data[0].usePpretion;
            this.fieldList = data;
          } else {
            this.fieldList = [];
          }
        })
        .catch((err) => {});
    },
    handleClick() {
      this.showTabs = true;
    },
    // 取消重置
    cancelRest() {
      this.screenField = [];
      this.screenField.push(this.copyObject(info));
      this.zn = {
        accurateSearch: "",
        includeSearch: "",
        notIncludeSearch: "",
      };
      this.bds = {
        whereToShow: "0",
        keywords: "",
      };
      this.sjyList.forEach((list) => {
        list.selectVal = 0;
        list.selectList = [];
      });
      this.ztInfo = {
        ztlm: "0",
        specialColumn_name: "",
      };
    },
    handleParam() {
      let param = {
        queryType: this.queryType,
      };
      if (this.queryType == 1) {
        param.screenField = this.screenField;
      } else if (this.queryType == 2) {
        Object.assign(param, this.zn);
      } else if (this.queryType == 3) {
        Object.assign(param, this.bds);
      } else if (this.queryType == 4) {
        // let sources = [];
        // this.sjyList.forEach((list) => {
        //   sources.push(...list.selectList);
        // });
        // param.sources = sources;
      }
      let sources = [];
      this.sjyList.forEach((list) => {
        sources.push(...list.selectList);
      });
      // param.sources = sources;
      let result = {
        sources: sources,
        multiFunctionQuery: param,
      };
      // if (this.ztInfo.ztlm == 1) {
      //   result.specialColumn_name = this.ztInfo.specialColumn_name;
      // }
      return result;
    },
    // 确定检索
    search() {
      let result = this.handleParam();
      this.$emit("gotoSearch", result);
    },
    // 存为专题栏目
    addColumn() {
      let result = this.handleParam();
      this.$prompt("", "存为专题栏目", {
        closeOnClickModal: false,
        inputPlaceholder: "请输入专题栏目的名称，长度不超过8个字",
        inputValidator: function(value) {
          if (value == null || value == "") {
            return "专题栏目的名称不能为空!";
          } else if (value.length > 8) {
            return "专题栏目的名称长度不得超过8个字！";
          }
          return true;
        },
      }).then(({ value }) => {
        result.specialColumn_name = value;
        this.$post(this.$Url.consultModule.addSpecialColumn, result).then(
          (res) => {
            let data = res.data;
            if (data) {
              this.$emit("reloadColumn");
              this.$message({
                type: "success",
                message: "保存成功！",
              });
            } else {
              this.$message({
                type: "warning",
                message: "保存失败！请您再试一次",
              });
            }
          }
        );
      });
    },
    copyObject(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
    addRow(idx) {
      this.screenField.splice(idx + 1, 0, this.copyObject(info));
    },
    reduceRow(idx) {
      this.screenField.splice(idx, 1);
    },
    valChange(idx) {
      let sjyList = this.sjyList[idx];
      sjyList.selectList = [];
      if (sjyList.selectVal) {
        sjyList.selectList = sjyList.list;
        // sjyList.list.forEach((list) => {
        //   sjyList.selectList.push(list);
        // });
      }
      this.$set(this.sjyList, idx, sjyList);
    },
    checkChange() {
      this.$forceUpdate(this.sjyList);
    },
  },
};
</script>
<style lang="scss">
.dialogClass{
  .el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button--primary:active,.el-button--primary:focus,.el-button--primary:hover{
  color: #FFF !important;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button:focus, .el-button:hover {
    color: $mainColor;
    border-color: $mainColor;
    background-color: $hoverColor;
}
}
</style>
<style lang="scss">
.el-message-box__btns{
  .el-button--primary {
    color: #FFF !important;
    background-color: $mainColor !important;
    border-color:$mainColor !important;
}
.el-button:hover,.el-button:active{
  color:  $mainColor;
  border-color:$mainColor;
}
}

</style>
<style lang="scss" scoped>

.searchGroup {
  // padding: 0 0.3rem;
  margin-top: 10px;
  // font-size: 0.14rem;

  .sg-wrapper {
    padding: 0 20px;
    background-color: #fff;
  }
  .el-icon-date:before {
    color: #666;
  }
  .sg-tabs {
    position: relative;
    .el-date-editor,
    .el-select {
      width: 100%;
    }
  }
  .sg-show {
    position: absolute;
    right: 10px;
    top: 0;
    .el-button--text{
      color: $mainColor;

    }
    i {
      color: #333;
      font-size: 16px;
    }
  }
  .el-button--medium {
    padding: 10px;
  }
  .tabZn {
    p {
      margin-bottom: 15px;
    }
    .span {
      display: inline-block;
      width: 130px;
      margin-right: 10px;
      text-align: right;
    }
  }
  .longInput {
    width: 320px;
  }
  .largeInput {
    width: 500px;
  }
  .textarea {
    margin: 10px 0 5px;
  }
  .tabBds {
    p {
      color: #999;
      // line-height: 21px;
    }
  }
  .sjy-con {
    max-height: 200px;
    overflow-y: auto;
  }
  .sjy {
    margin-bottom: 15px;
  }
  .checkboxGroup {
    padding: 0 20px;
    .el-checkbox {
      width: 150px;
      margin-top: 15px;
    }
  }
  .selectAll {
    margin-left: 10px;
    .el-checkbox__label {
      padding-left: 5px;
    }
  }
  .btnGroup {
    display: flex;
    padding: 10px 0;
    .btnLeft {
      display: flex;
      flex: 1;
      .el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color:$mainColor !important;
}
    }
    .btn {
      text-align: right;
      .el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color:$mainColor !important;
}
.el-button:hover,.el-button:active,.el-button:focus{
  color:  $mainColor;
  border-color:$mainColor;
}
    }
  }
  .bold {
    font-weight: bold;
  }
  .ds {
    margin-top: 10px;
  }
}
</style>
